package yunwo.cn.yzstation.api;

import android.content.Context;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;
import yunwo.cn.yzstation.base.Yzapp;
import yunwo.cn.yzstation.bean.OrderBean.StaTrackingInfo;
import yunwo.cn.yzstation.config.MyConstants;
import yunwo.cn.yzstation.utils.L;
import yunwo.cn.yzstation.utils.StringUtil;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public  class HttpManager {

    private static final String TAG = "HttpManager";

    private static String inCode;



    public static RequestCall hpptPost(String url,Map<String,String> params){
          RequestCall build = OkHttpUtils.post().url(url)
            .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
            .params(params)
            .build();
        return build;
    }
    public static RequestCall hpptGet(String url,Map<String,String> params){
        RequestCall build = OkHttpUtils.get().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .params(params)
                .build();
        return build;
    }
    public static RequestCall hpptPostString(String url,Map<String,String> params){
        Gson gson = new Gson();
        String s = gson.toJson(params);
        RequestCall build = OkHttpUtils.postString().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .content(s)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build();

        return build;
    }
    public static RequestCall hpptPostObj(String url,Map<String,Object> params){
        Gson gson = new Gson();
        String s = gson.toJson(params);
        RequestCall build = OkHttpUtils.postString().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .content(s)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build();

        return build;
    }

    public static RequestCall hpptPostPageString(String url,int page,int size,String orderBy,Map<String,Object> params){
        Gson gson = new Gson();
        Map<String,Object> totalParams = new HashMap<>();
        if (page != 0 && size != 0){
            Map<String,String> pageParam = new HashMap<>();
            pageParam.put("orderBy", orderBy);
            pageParam.put("pageNum",page+"");
            pageParam.put("pageSize",size+"");
            totalParams.put("page",pageParam);
        }
        if (params != null){
            totalParams.put("params",params);
        }
        String s = gson.toJson(totalParams);
        RequestCall build = OkHttpUtils.postString().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .content(s)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build();

        return build;
    }
    public static RequestCall hpptPostString3(String url,Map<String,Object> params){
        return HttpManager.hpptPostPageString(url,0,0,"create_date desc",params);
    }
    public static RequestCall hpptPostPageStringmer(String url,int page,int size,Map<String,Object> params){
        Gson gson = new Gson();
        Map<String,Object> totalParams = new HashMap<>();
        if (page != 0 && size != 0){
            Map<String,String> pageParam = new HashMap<>();

            pageParam.put("pageNum",page+"");
            pageParam.put("pageSize",size+"");
            totalParams.put("page",pageParam);
        }
        if (params != null){
            totalParams.put("params",params);
        }
        String s = gson.toJson(totalParams);
        RequestCall build = OkHttpUtils.postString().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .content(s)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build();

        return build;
    }




    public static RequestCall hpptPostString2(String url, StaTrackingInfo aClass){
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("params", aClass);
        String s = gson.toJson(map);
        RequestCall build = OkHttpUtils.postString().url(url)
                .addHeader("Authorization", Yzapp.getInstance().getAuthorization())
                .content(s)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build();

        return build;
    }



    /*private static String getParams(Map<String, Object> params) {

        // 使用SHA签名
        Gson gson = new Gson();
        Random rand = new Random();
        String rd = String.valueOf(rand.nextInt(1000));
        String time = String.valueOf(System.currentTimeMillis());
        params.put("time", time);
        params.put("rd", rd);
        String appId =  MyConstants.APP_INFO_ID;
        String appKey = MyConstants.APP_INFO_KEY;
        if(MyConstants.IP_ADDRESS.contains(MyConstants.TEST_ADDRESS)){
            appId = MyConstants.APP_INFO_TEST_ID;
            appKey = MyConstants.APP_INFO_TEST_KEY;
        }
        params.put("appId", appId);
        Map<String, Object> map1 = (Map<String, Object>) params.get("content");
        String param = gson.toJson(map1);
//        Log.d("wwwwwwwwwwwwww", param);
        param = StringEscapeUtils.unescapeJava(param);
//        Log.d("wwww", param);
        params.put("content", param);
        String[] arry = {appKey,ApplicationInfo.getInstance().getTokenId(), time, rd, param};
        Arrays.sort(arry);
        String sign = MD5.eccrypt(Arrays.toString(arry));
        params.put("sign", sign);
        return gson.toJson(params);
    }*/



    /**
     * post 请求
     *
     * @param context 如果填了context，那么isLogout必须为false，否则抛异常
     * @param params  请求传参
     * @param clazz   用于解析后台返回的json bean

     * @return 后台返回解析成功的bean，也就是clazz
     * @throws Exception
     */

 /*   public static <T> T httpPost(Context context, String url, Map<String, String> params, final Class<T> clazz) throws Exception {
        String className = context.getClass().getName();
        try {



             OkHttpUtils
                    .post()
                    .url(url)
                    .params(params)
                    .build()
                    .execute(new Callback<T>() {
                        @Override
                        public T parseNetworkResponse(Response response, int id) throws Exception {
                            String s = response.body().toString();
                            T bean = new Gson().fromJson(s, clazz);
                            return bean;
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(T response, int id) {

                        }
                    });


        } catch (Exception e) {

            e.printStackTrace();
            L.d(TAG, "Exception:请求错误 "+params.get("inCode"));
            return null;
        }
        return null;
    }
*/


  /*  private static String decodeResponse(HttpResponse httpResponse, String inCode) throws Exception {
        HttpManager.httpResponse = httpResponse;
        HttpManager.inCode = inCode;
        // 请求返回处理：解压缩、解密
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = httpResponse.getEntity();
            String responseBody = EntityUtils.getContentCharSet(entity);
            InputStream is = entity.getContent();
            InputStream inStream = null;
            inStream = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int iRead;
            StringBuffer out = new StringBuffer(200);
            while ((iRead = inStream.read(buffer)) != -1) {
                out.append(new String(buffer, 0, iRead, Charset.forName(responseBody)));
            }
            L.d(TAG, "返回：" + out.toString()+",inCode:"+inCode);
            return out.toString();
        } else {
            L.d(TAG, "请求失败，错误码" + statusCode+",inCode:"+inCode);
            return null;
        }
    }
*/
    /**
     * post 请求(添加附件)
     *

     * @param clazz  用于解析后台返回的json bean
     * @return 后台返回解析成功的bean，也就是clazz
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
/*    public static <T> T httpAddExtraPost(Map<String, Object> params, File file, Class<T> clazz) throws FileNotFoundException {
        if (file.length() == 0) {
            LogUtil.e(TAG, "没有文件");
            throw new FileNotFoundException("没有文件");
        }
        LogUtil.d(TAG,"file:"+file);
        HttpPost httpPost = null;
        HttpResponse httpResponse = null;
        MultipartEntityBuilder builder = null;
        try {
            Charset gbk = Charset.forName("GBK");
            Charset utf8 = Charset.forName("UTF-8");
            String userId = ApplicationInfo.getInstance().getUserId();
            if (!StringUtil.isEmpty(userId)) {
                params.put("uId", userId);
            }
            params.put("netType", NetUtil.getNetType());
            params.put("ver", UpdateVersionUtil.getVersionName(UIUtils.getContext()));
            String inCode = (String) params.get("inCode");
            String requestBody = getParams(params);
            builder = MultipartEntityBuilder.create();
            builder.setCharset(gbk);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addPart("json", new StringBody(requestBody, utf8));
            builder.addPart("file", new FileBody(file));
            LogUtil.d(TAG, "requestBody:" + requestBody);
            httpPost = new HttpPost(MyConstants.REQUESTURL);
            httpPost.setHeader("User-Agent", "App(Linux; U; Android)");
            HttpEntity httpEntity = builder.build();// 生成 HTTP POST 实体
            httpPost.setEntity(httpEntity);
            httpResponse = getHttpClient().execute(httpPost);
            return jsonParseToBean(decodeResponse(httpResponse, inCode), clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }*/

    // 解析json
    public static <T> T jsonParseToBean(String jsonString, Class<T> clazz) throws Exception {
        if (StringUtil.isEmpty(jsonString)) {
            return null;
        }
        Gson gson = new Gson();
        T t = null;
        try {
            t = gson.fromJson(jsonString, clazz);
        } catch (Exception e) {
            L.d(TAG, "json解析异常:\n" + jsonString);
            e.printStackTrace();
        }

        return t;
    }
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    private final static String ENCODE = "GBK";
}
